package com.sun.showcase.biz.basic.service.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sun.showcase.biz.basic.dao.ResourceInfoDao;
import com.sun.showcase.biz.basic.dao.UserResourceDao;
import com.sun.showcase.biz.basic.service.UserResourceService;
import com.sun.showcase.pojo.DataGrid;
import com.sun.showcase.pojo.Pager;
import com.sun.showcase.client.basic.domain.ResourceInfo;
import com.sun.showcase.client.basic.domain.UserResource;
import com.sun.showcase.client.basic.query.ResourceInfoQuery;
import com.sun.showcase.client.basic.query.UserResourceQuery;
import com.sun.showcase.utils.LoginContextHolder;
import com.sun.showcase.utils.TreeNode;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
@Service("userResourceService")
@Transactional
public class UserResourceServiceImpl implements UserResourceService{
	@Resource
	private UserResourceDao userResourceDao;
	
	@Resource
	private ResourceInfoDao resourceInfoDao;
	
	public void setResourceInfoDao(ResourceInfoDao dao) {
		this.resourceInfoDao = dao;
	}

	public void setUserResourceDao(UserResourceDao dao) {
		this.userResourceDao = dao;
	}

	public DataGrid datagrid(UserResourceQuery userResourceQuery) {
		DataGrid j = new DataGrid();
		Pager<UserResource> pager  = find(userResourceQuery);
		j.setRows(getQuerysFromEntitys(pager.getRecords()));
		j.setTotal(pager.getTotalRecords());
		return j;
	}

	private List<UserResourceQuery> getQuerysFromEntitys(List<UserResource> userResources) {
		List<UserResourceQuery> userResourceQuerys = new ArrayList<UserResourceQuery>();
		if (userResources != null && userResources.size() > 0) {
			for (UserResource tb : userResources) {
				UserResourceQuery b = new UserResourceQuery();
				BeanUtils.copyProperties(tb, b);
				userResourceQuerys.add(b);
			}
		}
		return userResourceQuerys;
	}

	private Pager<UserResource> find(UserResourceQuery userResourceQuery) {
		Page<UserResource> page = PageHelper.startPage(userResourceQuery.getPage().intValue(), userResourceQuery.getRows().intValue());
		
		List<UserResource> list = userResourceDao.findList(userResourceQuery);
		Pager<UserResource> pager = new Pager<UserResource>();
		pager.setRecords(list);
		pager.setTotalRecords(page.getTotal());
		return pager;
		
	}
	


	public UserResource add(UserResourceQuery userResourceQuery) {
		UserResource t = new UserResource();
		BeanUtils.copyProperties(userResourceQuery, t);
		userResourceDao.save(t);
		userResourceQuery.setUserId(t.getUserId());
		return t;
		
	}

	public void update(UserResourceQuery userResourceQuery) {
		UserResource t = userResourceDao.getById(userResourceQuery.getUserId());
	    if(t != null) {
	    	BeanUtils.copyProperties(userResourceQuery, t);
		}
	    userResourceDao.update(t);
	}

	public void delete(java.lang.String id) {
		if (id != null) {
			userResourceDao.deleteById(id);
		}
	}

	public UserResource get(UserResourceQuery userResourceQuery) {
		return userResourceDao.getById(userResourceQuery.getUserId());
	}

	public UserResource get(String id) {
		return userResourceDao.getById(id);
	}

	
	public List<UserResourceQuery> listAll(UserResourceQuery userResourceQuery) {
	    List<UserResource> list = userResourceDao.findList(userResourceQuery);
		List<UserResourceQuery> listQuery =getQuerysFromEntitys(list) ;
		return listQuery;
	}

	@Override
	public List<TreeNode> findResourceByUser(String userId) {
		
		Map<String, String> roleMap = null;
		String[] userArray = null;
		//角色资源
		List<ResourceInfo> roleResources = resourceInfoDao.findByGroup(userId);
		if(roleResources!=null&&roleResources.size()>0){
			
			roleMap = new HashMap<String, String>();
			for(int i=0;i<roleResources.size();i++){
				roleMap.put(roleResources.get(i).getId(), roleResources.get(i).getGroupName());
			}
		}
		
		//个人资源
		UserResourceQuery userResourceQuery = new UserResourceQuery();
		userResourceQuery.setUserId(userId);
		List<UserResourceQuery> userResources ;
		if(!StringUtils.isNotEmpty(userId)){
			userResources=null;
		}else{
			userResources=listAll(userResourceQuery);
		}
		
		
		if(userResources!=null&&userResources.size()>0){
			
			userArray = new String[userResources.size()];
			
			for(int j=0;j<userResources.size();j++){
				userArray[j] = userResources.get(j).getResourceId();
			}
		}
		
		List<TreeNode> listnode = new ArrayList<TreeNode>();

		List<ResourceInfo> listParent=resourceInfoDao.findParentResource();
		
		for(ResourceInfo resourceInfo:listParent){
			
			TreeNode treeNode = new TreeNode();
			
			treeNode.setId(resourceInfo.getId());
			
			treeNode.setText(resourceInfo.getName());
			
			Set<TreeNode> s = buildChidNodes(resourceInfo.getId(),roleMap,userArray);
			
			if(roleMap != null){
				if(roleMap.containsKey(resourceInfo.getId())){
					treeNode.setChecked("1");
					treeNode.setObj(roleMap.get(resourceInfo.getId()));
				}
			}
			
			if(userArray!=null){
				if(Arrays.asList(userArray).contains(resourceInfo.getId())){
					treeNode.setChecked("1");
				}
			}
			treeNode.setChildren(s);
			treeNode.setState("closed");
			listnode.add(treeNode);
		}
		
		return listnode;
	}
	
	private Set<TreeNode> buildChidNodes(String parentId,Map<String, String> roleMap,String[] userArray){
		
		List<ResourceInfo> resourceList = resourceInfoDao.findChildResourceByparentId(parentId);
		
		Set<TreeNode> ss = new LinkedHashSet<TreeNode>();
		
		for(int i=0; i < resourceList.size(); i++){
			
			ResourceInfo r = resourceList.get(i);
			
			TreeNode nodes = new TreeNode();
			
			nodes.setId(r.getId().toString());
			
			nodes.setText(r.getName());
			
			if(buildChidNodes(r.getId(),roleMap,userArray).size()>0){
				nodes.setChildren(buildChidNodes(r.getId(),roleMap,userArray));
				nodes.setState("closed");
			}
			
			if(roleMap != null){
				if(roleMap.containsKey(r.getId().toString())){
					nodes.setChecked("1");
					nodes.setObj(roleMap.get(r.getId().toString()));
				}
			}
			
			if(userArray!=null){
				if(Arrays.asList(userArray).contains(r.getId().toString())){
					nodes.setChecked("1");
				}
			}
			
			ss.add(nodes);
		}
		return ss;
	}
	
	@Override
	public void deleteByResource(String resouceId) {
		
		userResourceDao.deleteByResource(resouceId);
	}

	@Override
	public List<TreeNode> findResourceByUserID(String userId) {
		Map<String, String> roleMap = null;
		String[] userArray = null;
		//角色资源
		List<ResourceInfo> roleResources = resourceInfoDao.findByGroup(userId);
		if(roleResources!=null&&roleResources.size()>0){
			
			roleMap = new HashMap<String, String>();
			for(int i=0;i<roleResources.size();i++){
				roleMap.put(roleResources.get(i).getId(), roleResources.get(i).getGroupName());
			}
		}
		
		//个人资源
		UserResourceQuery userResourceQuery = new UserResourceQuery();
		userResourceQuery.setUserId(userId);
		List<UserResourceQuery> userResources = listAll(userResourceQuery);
		if(!StringUtils.isNotEmpty(userId)){
			userResources=null;
		}
		
		if(userResources!=null&&userResources.size()>0){
			
			userArray = new String[userResources.size()];
			
			for(int j=0;j<userResources.size();j++){
				userArray[j] = userResources.get(j).getResourceId();
			}
		}
		
		List<TreeNode> listnode = new ArrayList<TreeNode>();

		List<ResourceInfo> listParent=resourceInfoDao.findParentResource();
		String id= LoginContextHolder.get().getUserId();
		for(ResourceInfo resourceInfo:listParent){
			
			TreeNode treeNode = new TreeNode();
			
			treeNode.setId(resourceInfo.getId());
			
			treeNode.setText(resourceInfo.getName());
			
			Set<TreeNode> s = buildChidNodesByUser(resourceInfo.getId(),roleMap,userArray,id);
			
			if(roleMap != null){
				if(roleMap.containsKey(resourceInfo.getId())){
					treeNode.setChecked("1");
					treeNode.setObj(roleMap.get(resourceInfo.getId()));
				}
			}
			
			if(userArray!=null){
				if(Arrays.asList(userArray).contains(resourceInfo.getId())){
					treeNode.setChecked("1");
				}
			}
			treeNode.setChildren(s);
			treeNode.setState("closed");
			listnode.add(treeNode);
		}
		
		return listnode;
	}

	private Set<TreeNode> buildChidNodesByUser(String id,
			Map<String, String> roleMap, String[] userArray,String userId) {
		ResourceInfoQuery query=new ResourceInfoQuery();
		query.setParentId(id);
		query.setUserId(userId);
		List<ResourceInfo> resourceList = resourceInfoDao.findChildByParentId(query);
		
		Set<TreeNode> ss = new LinkedHashSet<TreeNode>();
		
		for(int i=0; i < resourceList.size(); i++){
			
			ResourceInfo r = resourceList.get(i);
			
			TreeNode nodes = new TreeNode();
			
			nodes.setId(r.getId().toString());
			
			nodes.setText(r.getName());
			
			if(buildChidNodes(r.getId(),roleMap,userArray).size()>0){
				nodes.setChildren(buildChidNodes(r.getId(),roleMap,userArray));
				nodes.setState("closed");
			}
			
			if(roleMap != null){
				if(roleMap.containsKey(r.getId().toString())){
					nodes.setChecked("1");
					nodes.setObj(roleMap.get(r.getId().toString()));
				}
			}
			
			if(userArray!=null){
				if(Arrays.asList(userArray).contains(r.getId().toString())){
					nodes.setChecked("1");
				}
			}
			
			ss.add(nodes);
		}
		return ss;
	}
}
